﻿<%@ WebHandler Language="C#" Class="Auth" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;
using System.DirectoryServices;
using System.Configuration;
using System.Linq;

public class Auth : IHttpHandler, IRequiresSessionState {
    
    public void ProcessRequest (HttpContext context) {
        AjaxResponse axresponse = new AjaxResponse();
        context.Response.ContentType = "application/json";
        string action = AHMIDEAFunctions.ContextPostData(context, "action").ToUpper();
        switch (action)
	    {
		    case "LOGIN":
                axresponse = Login(context);
                break;
		    case "LOGOUT":
                axresponse = Logout(context);
                break;
                
	    }
        context.Response.Write(axresponse.GenerateJSON());
    }
 

    public bool IsReusable {
        get {
            return false;
        }
    }
    
    private AjaxResponse Logout(HttpContext context) {
        AjaxResponse axresponse = new AjaxResponse();
        FormsAuthentication.SignOut();
        
        // remove menu cache
        string cachepath = ConfigurationManager.AppSettings["cachePath"];
        string cacheFile = AHMIDEAFunctions.CalculateMD5Hash(HttpContext.Current.User.Identity.Name);
        string cacheFilePath = System.IO.Path.Combine(cachepath, "MENU_" + cacheFile);
        if (System.IO.File.Exists(cacheFilePath)) {
            System.IO.File.Delete(cacheFilePath);
        }
        
        axresponse.Status = "1";
        axresponse.RedirectUrl = FormsAuthentication.LoginUrl;
        axresponse.Message = "You have been sucessfully logged out.";
        return axresponse;
    }
    
    private AjaxResponse Login(HttpContext context) {
        AjaxResponse axresponse = new AjaxResponse();
        string username = AHMIDEAFunctions.ContextPostData(context, "user");
        string password = AHMIDEAFunctions.ContextPostData(context, "pass");
        string redirect = AHMIDEAFunctions.ContextPostData(context, "ReturnUrl");

        string[] aruser = username.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);

        if (aruser.Length > 1)
        {
            string domain = aruser[0].ToUpper();
            string uname = aruser[1];
            string displayname = "";
            string email = "";
            string nrp = "";
            
            switch (domain) 
	        {
		        case "SYSTEM" :
                    bool authenticated = false;
                    using(DC_AHMIDEADataContext dc = new DC_AHMIDEADataContext())
	                {
		                var res = dc.SPAHMIDEA_UserAuthenticate(uname,password);
                        foreach (SPAHMIDEA_UserAuthenticateResult item in res)
	                    {
                            authenticated = true;
                            displayname = item.vdisplayname;
                            email = item.vemail;
                            nrp = item.vnrp;
                            break;                   
	                    }
	                }

                    if (authenticated)
                    {
                        string cookieName = FormsAuthentication.FormsCookieName;
                        string userDataString = domain + "|" + uname + "|" + displayname + "|" + email + "|" + nrp;
                        int authTimeOut = 30;
                        Int32.TryParse(System.Configuration.ConfigurationManager.AppSettings["_CONFIG_AUTH_TIMEOUT"],out authTimeOut);
                        //context.Session["userData"] = userDataString;
                        //context.Session["userAddr"]  = context.Request.UserHostAddress;
                        
                        
                        FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(2, cookieName, DateTime.Now, DateTime.Now.AddMinutes(authTimeOut), false, userDataString);
                        HttpCookie authCookie = new HttpCookie(cookieName, FormsAuthentication.Encrypt(newTicket));
                        context.Response.Cookies.Add(authCookie);
                        axresponse.Status = "1";
                        axresponse.RedirectUrl = "Default.aspx";
                        if (!string.IsNullOrEmpty(redirect) && redirect.Contains("#"))
                        {
                            axresponse.RedirectUrl = redirect;
                        }
                        else
                        {
                            axresponse.RedirectUrl = FormsAuthentication.GetRedirectUrl(username, false);
                        }
                    }
                    else {
                        axresponse.Status = "0";
                        axresponse.Message = "Invalid username / password.";
                    }
                    
                    break;
                default:
                    try
                    {
                        DirectoryEntry entry = new DirectoryEntry(ConfigurationManager.AppSettings["ldapUrl"], username, password);
                        object obj = entry.NativeObject;

                        using (DC_AHMIDEADataContext dc = new DC_AHMIDEADataContext())
                        {
                            var pu = dc.AHMIDEA_MSTUSERs.FirstOrDefault(p => p.vuserid.ToLower()== username.ToLower());
                            //if (pu == null) {
                            //    AHMIDEA_MSTUSER usr = new AHMIDEA_MSTUSER();
                            //    usr.vuserid = username;
                            //    usr.dbegineff = DateTime.Now.AddDays(-1);
                            //    usr.dlasteff = DateTime.Now.AddYears(100);
                            //    dc.AHMIDEA_MSTUSERs.InsertOnSubmit(usr);
                            //    dc.SubmitChanges();
                            //}
                            
                            var pr = dc.AHMIDEA_MSTPROFILEs.FirstOrDefault(p => p.vuserid.ToLower() == username.ToLower());

                            if (pr != null)
                            {
                                displayname = pr.vdisplayname;
                                email = pr.vemail;
                                nrp = pr.vnrp;
                            }
                            else {
                                AHMIDEA_MSTPROFILE prof = new AHMIDEA_MSTPROFILE();
                                prof.vuserid = username;
                                prof.vdisplayname = username;
                                dc.AHMIDEA_MSTPROFILEs.InsertOnSubmit(prof);
                                dc.SubmitChanges();                                
                            }
                        }
                        
                        string cookieName = FormsAuthentication.FormsCookieName;
                        string userDataString = domain + "|" + uname + "|" + displayname + "|" + email + "|" + nrp;
                        int authTimeOut = 30;
                        Int32.TryParse(System.Configuration.ConfigurationManager.AppSettings["_CONFIG_AUTH_TIMEOUT"], out authTimeOut);

                        FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(2, cookieName, DateTime.Now, DateTime.Now.AddMinutes(authTimeOut), false, userDataString);
                        HttpCookie authCookie = new HttpCookie(cookieName, FormsAuthentication.Encrypt(newTicket));
                        context.Response.Cookies.Add(authCookie);
                        axresponse.Status = "1";
                        axresponse.RedirectUrl = "Default.aspx";
                        if (!string.IsNullOrEmpty(redirect) && redirect.Contains("#"))
                        {
                            axresponse.RedirectUrl = redirect;
                        }
                        else
                        {
                            axresponse.RedirectUrl = FormsAuthentication.GetRedirectUrl(username, false);
                        }
                    }
                    catch (DirectoryServicesCOMException dex)
                    {
                        axresponse.Status = "0";
                        axresponse.Message = string.Join(" ",dex.Message.Split());
                        Logging.WriteLog("ERROR : " + dex.Message);
                    }
                    catch (Exception ex)
                    {
                        axresponse.Status = "0";
                        axresponse.Message = string.Join(" ", ex.Message.Split());
                        Logging.WriteLog("ERROR : " + ex.Message);
                    }
                    break;
	        }
        }
        else {
            axresponse.Message = "Invalid username format. Please use domain\\\\username format instead.";
        }
        return axresponse;
    }



}